﻿using Newtonsoft.Json;
using System;
using System.Xml;

namespace ThresholdAssistant.Tools.Extensions
{
    /// <summary>
    /// XML转换扩展类
    /// </summary>
    public static class XmlConvertUtil
    {
        /// <summary>
        /// Xml反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(this string xml)
        {
            T result = default;
            try
            {
                if (string.IsNullOrEmpty(xml))
                    return result;

                var doc = new XmlDocument();
                doc.LoadXml(xml);
                var jsonValue = JsonConvert.SerializeXmlNode(doc.DocumentElement);
                if (!string.IsNullOrEmpty(jsonValue))
                {
                    result = JsonConvert.DeserializeObject<T>(jsonValue);
                }
            }
            catch (Exception)
            {

            }
            return result;
        }
    }
}